package com.example.multi.gateway.filter;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author
 * @description
 * @create 2022-05-18 15:20
 */
@Component
public class CustomFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(CustomFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpRequest serverHttpRequest = exchange.getRequest();

            String ip = serverHttpRequest.getLocalAddress().toString();
            String path = serverHttpRequest.getPath().toString();
            HttpHeaders httpHeaders = serverHttpRequest.getHeaders();

            logger.debug("ip:{},path:{}", ip, path);
            logger.debug("header:{}", JSON.toJSON(httpHeaders));
        } catch (Exception e) {
            logger.error("[filter]", e);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
